<template>
    <view>
        <slot name="top" :pay="pay"></slot>
        <view v-if="page_type=='cart'" class="padding-left-24 padding-top-20 text-666 text-sm">共{{page.item_attr_length}}件宝贝</view>
        <template v-if="page.item_attr_length > 0">
            <checkbox-group class="block" @change="changePayItemAttrIds">
                <view style="margin: 20rpx 24rpx 24rpx 24rpx" class="bg-white radius-16" v-for="(seller_user_id, key) in page.order_seller_list"
                    :key="seller_user_id">
                    <view v-if="page_type=='cart'||page_type=='pay'" class="flex align-center padding-tb-10">
                        <view v-if="page_type=='cart'" class="padding-lr-24">
                            <checkbox-group>
                                <checkbox @tap="changePaySellerUserId(seller_user_id)" class='round nddyny' :value="seller_user_id"
                                    :class="pay.seller_user_ids|inArray(seller_user_id)?'checked':''" :checked="pay.seller_user_ids|inArray(seller_user_id)?true:false"></checkbox>
                            </checkbox-group>
                        </view>
                        <view :class="[page_type=='pay'?'padding-lr-24':'']" class="cu-list menu flex flex-direction">
                            <nMenuItemRow1 :uri="'/seller/item/list?seller_id='+seller_user_id+'&buy_mode='+buy_mode"
                                style_item="padding: 0; width: 602rpx;" class_title="text-lg" class_left="text-xxl"
                                left_icon="cuIcon-shop" :right_icon="page_type!='pay'?'arrow':''" :title="page.seller_list[seller_user_id].name"></nMenuItemRow1>
                        </view>
                    </view>
                    <view :class="[page_type=='cart'||page_type=='pay'?'padding-lr-24':'']" class="padding-bottom-10">
                        <view class="flex" v-for="(item_attr_info, key) in page.cart_list[seller_user_id].item_attr_list"
                            :key="key">
                            <view v-if="page_type=='cart'" class="flex align-center padding-right-24" style="width: 76rpx; height: 190rpx;">
                                <checkbox class='round nddyny' :value="item_attr_info.item_attr_id" :class="pay.item_attr_ids|inArray(item_attr_info.item_attr_id)?'checked':''"
                                    :checked="pay.item_attr_ids|inArray(item_attr_info.item_attr_id)?true:false"></checkbox>
                            </view>
                            <itemInfo :buy_mode="buy_mode" class="padding-bottom-20" :is_cart="page_type!='pay'"
                                :is_pay="page_type=='pay'" :item_attr_info="item_attr_info" :item_content_width="page_type=='cart'?'374rpx':(page_type=='item'?'438rpx':(page_type=='pay'?'450rpx':null))"
                                :seller_user_id="seller_user_id" :item_info="page.cart_list[seller_user_id].item_list[item_attr_info.item_id]"
                                :cart_item_attr_info="page.cart_list[seller_user_id].items[item_attr_info.item_attr_id]"
                                :itemAttrCartUpdate="itemAttrCartUpdate" :itemInfoDialogShow="_itemInfoDialogShow"></itemInfo>
                        </view>
                    </view>
                </view>
            </checkbox-group>
        </template>
        <emptyList v-else style="margin: 20rpx 24rpx 24rpx 24rpx" class="bg-white radius-16" :empty_list_title="page_type=='pay'?'无要购买的商品':'购物车无商品'"></emptyList>
        <slot name="foot"></slot>
        <foot v-if="page_type=='cart'||page_type=='pay'" style_bg="#505052" :style_foot="page_type=='cart'?'bottom:100rpx':''">
            <template #content>
                <view class="flex width-100p align-center text-white">
                    <view v-if="page_type=='cart'" @tap="changePaySellerUserId()" class="width-100p flex align-center padding-left-30 padding-right-10"
                        style="width: 170rpx;">
                        <checkbox-group>
                            <checkbox class='round nddyny' :class="pay.is_check_all_item_attr?'checked':''" :checked="pay.is_check_all_item_attr"></checkbox>
                        </checkbox-group>
                        <view class="padding-left-14">全选</view>
                    </view>
                    <view class="flex justify-between align-center width-100p" :style="page_type=='pay'?'width: 750rpx;':'width: 580rpx;'">
                        <view class="padding-left-10 text-cut-1" :style="page_type=='pay'?'width: 540rpx;':'width: 370rpx;'"
                            :class="page_type=='pay'?'padding-right-20':''">
                            <view v-if="page_is_delete == false || page_type=='pay'" class="text-gray" :class="[page_type=='pay'?'text-right':'']">
                                <view class="flex align-end" style="height: 58rpx;" :class="[page_type=='pay'?'justify-end':'']">
                                    <view class="text-bold text-white padding-bottom-10" style="line-height: 1em;">
                                        <text v-if="page_type=='pay'" class="text-gray text-sm">
                                            共{{page.total_item_attr_amount}}件，
                                        </text>
                                        <text>￥</text>
                                        <text class="text-xl">
                                            <text v-if="page_type=='pay'">{{pay.price_info.pay_order_price | floor}}</text>
                                            <text v-else>{{pay.price_info.total_item_price | floor}}</text>
                                        </text>
                                        <text class="text-through text-gray margin-left-10 text-13">
                                            ￥
                                            <text style="margin-left: -4rpx">
                                                <text v-if="page_type=='pay'">{{pay.price_info.total_oprice | floor}}</text>
                                                <text v-else>{{pay.price_info.total_item_oprice | floor}}</text>
                                            </text>
                                        </text>
                                    </view>
                                </view>
                                <view class="text-11 text-cut-2" style="height: 42rpx; line-height: 1em;">
                                    <text v-if="page_type=='pay'">含</text>
                                    <text v-else>不含</text>
                                    <text v-if="page_type=='pay'">
                                        <text v-if="buy_mode!='1' && pay.price_info.total_recv_price > 0" class="padding-right-10">
                                            <text v-if="buy_mode=='0'">配送费</text>
                                            <text v-if="buy_mode=='2'">运费</text>
                                            <text>￥{{pay.price_info.total_recv_price | floor}}</text>
                                        </text>
                                    </text>
                                    <text>包装费￥{{pay.price_info.total_pack_price | floor}}</text>
                                    <text class="margin-left-10">
                                        送金券 {{pay.price_info.total_user_gold_coupon_amount | floor(4)}}
                                    </text>
                                </view>
                            </view>
                        </view>
                        <view style="width: 210rpx">
                            <template v-if="page_is_delete == false || page_type=='pay'">
                                <view @tap="paySubmit(buy_mode, pay.item_attr_ids, page.item_attr_list, page.cart_item_attr_list)"
                                    v-if="pay.item_attr_ids.length > 0 || page_type == 'pay'" class="cu-btn text-lg bg-nddyny"
                                    style="width: 100%; height: 100rpx;">去结算
                                </view>
                                <view v-else class="cu-btn text-lg bg-cart-submit-gray" style="width: 100%; height: 100rpx;">去结算</view>
                            </template>
                            <template v-else>
                                <view @tap="()=>{itemAttrCartDelete()}" v-if="pay.item_attr_ids.length > 0" class="cu-btn text-lg bg-nddyny"
                                    style="width: 100%; height: 100rpx;">删除
                                </view>
                                <view v-else class="cu-btn text-lg bg-cart-submit-gray" style="width: 100%; height: 100rpx;">删除</view>
                            </template>
                        </view>
                    </view>
                </view>
            </template>
        </foot>
        <modalDialog v-if="command_refresh_dialog.show" :is_hide_cancel="true" :show.sync="command_refresh_dialog.show"
            :confirm="command_refresh_dialog.confirm" :content="command_refresh_dialog.content"></modalDialog>
    </view>
</template>

<script>
    import itemInfo from './itemInfo.vue';

    export default {
        components: {
            itemInfo,
        },
        props: [
            'page_type', 'page_is_delete', 'seller_user_id', 'cart',
            'isUpdateCartCallback', 'itemInfoDialogShow', 'paySubmit'
        ],
        data() {
            return {
                seller_type: this.$store.state.user.is_seller_firm == 1 ? 1 : 0,
                buy_mode: null,
                command_refresh_dialog: {
                    show: false,
                    content: '',
                    confirm: null,
                },
                page: {
                    item_attr_length: 0,
                    total_item_attr_amount: 0,
                    order_seller_list: [],
                    seller_list: null,
                    cart_list: null,
                    cart_item_list: null,
                    cart_item_attr_list: null,
                    item_attr_list: null,
                    price_info: {},
                },
                pay: {
                    is_check_all_item_attr: false,
                    item_attr_ids: [],
                    seller_user_ids: [],
                    price_info: {},
                    price_info_bak: {},
                }
            }
        },
        watch: {
            'pay.item_attr_ids'(item_attr_ids) {
                if (!this.page.cart_list || this.page_type != 'cart') {
                    return;
                }
                this.setPaySellerUserIdsIsCheckAllItemAttrCheck();
                this.payItemAttrIdsPrice();
            }
        },
        methods: {
            // 初始化支付相关数据
            payInit() {
                this.pay.is_check_all_item_attr = false;
                this.pay.item_attr_ids = [];
                this.pay.seller_user_ids = [];
                this.pay.price_info = this.$nddyny.object.copy(this.pay.price_info_bak);
            },
            setBuyMode(buy_mode) {
                this.buy_mode = buy_mode;
            },
            // 初始化页面
            pageInit(cur_key) {
                if (!this.$store.state.user.auth_token) {
                    return;
                }
                if (cur_key) {
                    this.setBuyMode(this.$dict.seller_buy_mode_key2int[cur_key]);
                }
                if (this.buy_mode === null || this.buy_mode == undefined) {
                    return;
                }
                // 只有切换 buy_mode 的时候才初始化
                if (cur_key) {
                    this.payInit();
                }
                this.$api.post(this, {
                    url: '/seller/itemCart/list',
                    data_key: null,
                    data_append: {
                        page_type: this.page_type,
                        seller_user_id: this.seller_user_id,
                        seller_type: this.seller_type,
                        buy_mode: this.buy_mode,
                    },
                    success: (Result, data_key) => {
                        this.setCartList(Result, data_key, 'pageInit');
                    }
                });
            },
            // 选择商品时
            changePayItemAttrIds(e) {
                this.pay.item_attr_ids = e.target.value;
            },
            // 设置商家或全选check
            setPaySellerUserIdsIsCheckAllItemAttrCheck() {
                let pay_seller_user_ids = [];
                Object.keys(this.page.cart_list).forEach(seller_user_id => {
                    let cart_info = this.page.cart_list[seller_user_id];
                    let cart_item_attr_ids = this.getNormalItemAttrIds(cart_info.item_attr_list);
                    if (cart_item_attr_ids.length > 0 &&
                        this.$nddyny.array.diff(cart_item_attr_ids, this.pay.item_attr_ids).length == 0) {
                        pay_seller_user_ids.push(seller_user_id);
                    }
                })
                this.pay.seller_user_ids = pay_seller_user_ids;
                if (this.pay.seller_user_ids.length != 0 &&
                    this.pay.seller_user_ids.length == Object.keys(this.page.cart_list).length) {
                    this.pay.is_check_all_item_attr = true;
                } else {
                    this.pay.is_check_all_item_attr = false;
                }
            },
            // 根据属性列表取出所有正常的属性ID
            getNormalItemAttrIds(item_attr_list) {
                let cart_item_attr_ids = [];
                Object.keys(item_attr_list).forEach(key => {
                    cart_item_attr_ids.push(item_attr_list[key].item_attr_id);
                })
                return cart_item_attr_ids;
            },
            // 选择商家或全选时
            changePaySellerUserId(seller_user_id) {
                if (!seller_user_id) {
                    // 全选
                    if (this.pay.is_check_all_item_attr == false) {
                        let item_attr_ids = [];
                        Object.keys(this.page.cart_list).forEach(seller_user_id => {
                            let cart_item_attr_ids = this.getNormalItemAttrIds(
                                this.page.cart_list[seller_user_id].item_attr_list
                            );
                            item_attr_ids = item_attr_ids.concat(cart_item_attr_ids)
                        })
                        this.pay.item_attr_ids = item_attr_ids;
                    } else {
                        this.pay.item_attr_ids = [];
                    }
                } else {
                    let cart_item_attr_ids = this.getNormalItemAttrIds(this.page.cart_list[seller_user_id].item_attr_list);
                    if (this.pay.seller_user_ids.includes(seller_user_id)) {
                        // 取消选择商家
                        this.pay.item_attr_ids = this.$nddyny.array.diff(
                            this.pay.item_attr_ids,
                            cart_item_attr_ids
                        )
                    } else {
                        // 选择商家
                        this.pay.item_attr_ids = this.$nddyny.array.unique(
                            this.pay.item_attr_ids.concat(cart_item_attr_ids)
                        );
                    }
                }
            },
            // 修改购物车商品数量
            itemAttrCartUpdate(crud_type, item_info, item_attr_id, input_item_amount) {
                let item_id = item_info.item_id;
                item_attr_id = item_attr_id || item_info.item_attr_id;
                let buy_amount_min = item_info.buy_amount_min;
                let amount = 1;
                let seller_user_id = item_info.seller_user_id;
                // 如果购物车中有要修改的商品
                if (crud_type != 2) {
                    if (this.page.cart_list &&
                        this.page.cart_list[seller_user_id] &&
                        this.page.cart_list[seller_user_id].items[item_attr_id]) {
                        if (crud_type == 0) {
                            // 增加商品数量
                            amount = this.page.cart_list[seller_user_id].items[item_attr_id].amount * 1 + 1;
                        } else {
                            // 减少商品数量
                            amount = this.page.cart_list[seller_user_id].items[item_attr_id].amount * 1 - 1;
                            if (amount < buy_amount_min) {
                                amount = 0;
                            }
                        }
                    } else if (crud_type == 0) {
                        amount = buy_amount_min > 0 ? buy_amount_min : 1;
                    } else {
                        return;
                    }
                } else {
                    amount = input_item_amount
                }
                amount = amount < 0 ? 0 : amount;

                let item_list = {};
                item_list[seller_user_id] = {};
                item_list[seller_user_id][item_attr_id] = {
                    item_id,
                    item_attr_id,
                    amount
                };
                this.itemAttrCartUpdateApi(item_list);
            },
            // 批量删除
            itemAttrCartDelete(item_attr_ids) {
                if (!item_attr_ids) {
                    item_attr_ids = this.pay.item_attr_ids;
                }
                let item_list = {};
                item_attr_ids.forEach(item_attr_id => {
                    let item_attr_info = this.page.item_attr_list[item_attr_id];
                    if (!item_list[item_attr_info.user_id]) {
                        item_list[item_attr_info.user_id] = {};
                    }
                    item_list[item_attr_info.user_id][item_attr_id] = {
                        item_id: item_attr_info.item_id,
                        item_attr_id,
                        amount: 0
                    };
                })
                this.itemAttrCartUpdateApi(item_list);
            },
            // 全部删除
            itemAttrCartClear() {
                this.$api.post(this, {
                    url: '/seller/ItemCart/clear',
                    data_key: null,
                    data_append: {
                        page_type: this.page_type,
                        seller_user_id: this.seller_user_id,
                        seller_type: this.seller_type,
                        buy_mode: this.buy_mode,
                    },
                    success: (Result, data_key) => {
                        this.setCartList(Result, data_key, 'itemAttrCartClear');
                    }
                });
            },
            // 修改购物车的接口
            itemAttrCartUpdateApi(item_list) {
                this.$api.post(this, {
                    url: '/seller/ItemCart/update',
                    data_key: null,
                    data_append: {
                        page_type: this.page_type,
                        seller_type: this.seller_type,
                        buy_mode: this.buy_mode,
                        item_list: JSON.stringify(item_list),
                    },
                    success: (Result, data_key) => {
                        this.setCartList(Result, data_key, 'itemAttrCartUpdateApi', item_list);
                    }
                });
            },
            // 设置页面列表
            setCartList(Result, data_key, function_name, api_item_list) {
                if (this.$R.noSuccess(Result)) {
                    if (!Result.message) {
                        this.$api.form.toast(this, Result, data_key);
                        return;
                    }
                    this.command_refresh_dialog.show = true;
                    this.command_refresh_dialog.content = Result.message;
                    this.command_refresh_dialog.confirm = () => {
                        this.command_refresh_dialog.show = false;
                    }
                    return;
                }
                if (function_name != 'pageInit' && Result.result.fail_messages && Result.result.fail_messages.length >
                    0) {
                    if (this.page_type == 'cart' || this.page_type == 'pay') {
                        this.command_refresh_dialog.show = true;
                        this.command_refresh_dialog.content = Result.result.fail_messages;
                        this.command_refresh_dialog.confirm = () => {
                            this.command_refresh_dialog.show = false;
                        }
                    }
                    if (this.isUpdateCartCallback) {
                        this.isUpdateCartCallback(Result.result.fail_messages);
                    }
                }
                let result_cart_list = Result.result.cart_list;
                let result_item_attr_list = Result.result.item_attr_list;
                let result_item_list = Result.result.item_list;
                let page_seller_list = Result.result.seller_list;
                let seller_item_list = {};
                Object.keys(result_item_list).forEach(item_id => {
                    let info = result_item_list[item_id];
                    if (!seller_item_list[info.seller_user_id]) {
                        seller_item_list[info.seller_user_id] = {};
                    }
                    seller_item_list[info.seller_user_id][item_id] = info;
                })
                let seller_item_attr_list = {};
                let page_item_attr_list = {};
                let page_item_attr_length = 0;
                Object.keys(result_item_attr_list).forEach(item_attr_id => {
                    let result_item_attr_info = result_item_attr_list[item_attr_id];
                    let seller_user_id = result_item_attr_info.user_id;
                    if (!seller_item_attr_list[seller_user_id]) {
                        seller_item_attr_list[seller_user_id] = {};
                    }
                    seller_item_attr_list[seller_user_id][item_attr_id] = result_item_attr_info;
                    page_item_attr_list[item_attr_id] = result_item_attr_info;
                    page_item_attr_length += 1;
                })
                Object.keys(seller_item_attr_list).forEach(seller_user_id => {
                    let item_attr_list = seller_item_attr_list[seller_user_id];
                    Object.keys(item_attr_list).forEach(item_attr_id => {
                        let item_attr_info = item_attr_list[item_attr_id];
                        let item_info = seller_item_list[seller_user_id][item_attr_info.item_id];
                        item_attr_info.true_sort = item_info.item_sort * 1 +
                            item_attr_info.sort / 10000000;
                    })
                    seller_item_attr_list[seller_user_id] = this.$nddyny.object.sort(
                        item_attr_list, 'true_sort', 'item_attr_id', 'id_'
                    );
                })
                let page_total_item_attr_amount = 0;
                let page_cart_list = {};
                let order_seller_list = [];
                let page_cart_item_list = {};
                let page_cart_item_attr_list = {};
                Object.keys(result_cart_list).forEach(result_cart_key => {
                    let result_cart_info = result_cart_list[result_cart_key];
                    let result_cart_info_items = result_cart_info.items;
                    result_cart_info.items = {};
                    result_cart_info_items.forEach(item_attr_info => {
                        let item_id = item_attr_info.item_id;
                        let item_attr_id = item_attr_info.item_attr_id;
                        if (page_cart_item_list[item_id]) {
                            page_cart_item_list[item_id].amount =
                                page_cart_item_list[item_id].amount * 1 + item_attr_info.amount * 1;
                            page_cart_item_list[item_id].is_sub = false;
                        } else {
                            page_cart_item_list[item_id] = this.$nddyny.object.copy(item_attr_info);
                            page_cart_item_list[item_id].is_sub = true;
                        }
                        page_cart_item_attr_list[item_attr_id] = item_attr_info;
                        result_cart_info.items[item_attr_id] = item_attr_info;
                        page_total_item_attr_amount += item_attr_info.amount * 1;
                    })
                    order_seller_list.push(result_cart_info.seller_user_id + '');
                    page_cart_list[result_cart_key] = Object.assign(result_cart_info, {
                        item_list: seller_item_list[result_cart_info.seller_user_id],
                        item_attr_list: seller_item_attr_list[result_cart_info.seller_user_id]
                    });
                })
                this.page.cart_item_list = page_cart_item_list;
                this.page.cart_item_attr_list = page_cart_item_attr_list;
                this.page.item_attr_length = page_item_attr_length;
                this.page.total_item_attr_amount = page_total_item_attr_amount;
                this.page.order_seller_list = order_seller_list;
                this.page.seller_list = page_seller_list;
                this.page.cart_list = page_cart_list;
                this.page.item_attr_list = page_item_attr_list;
                this.page.price_info = Result.result.price_info;
                this.pay.item_attr_ids = this.$nddyny.array.intersect(
                    this.pay.item_attr_ids,
                    Object.keys(page_item_attr_list)
                );
                if (this.cart) {
                    let cart = {
                        cart_item_list: this.page.cart_item_list,
                        cart_item_attr_list: this.page.cart_item_attr_list,
                        item_attr_length: this.page.item_attr_length,
                        order_seller_list: this.page.order_seller_list,
                        seller_list: this.page.seller_list,
                        cart_list: this.page.cart_list,
                        item_attr_list: this.page.item_attr_list,
                        price_info: this.page.price_info
                    }
                    this.$emit('update:cart', Object.assign({}, this.cart, cart));
                }
                if (api_item_list && Result.result.is_update_cart == '1') {
                    if (this.page_type == 'cart' || this.page_type == 'pay') {
                        this.command_refresh_dialog.show = true;
                        this.command_refresh_dialog.content =
                            Result.result.fail_messages && Result.result.fail_messages.length > 0 ? Result.result.fail_messages :
                            '商品有变';
                        this.command_refresh_dialog.confirm = () => {
                            this.command_refresh_dialog.show = false;
                        }
                    }
                    if (this.isUpdateCartCallback) {
                        this.isUpdateCartCallback(
                            Result.result.fail_messages && Result.result.fail_messages.length > 0 ? Result.result.fail_messages :
                            '商品有变'
                        );
                    }
                }
                if (this.page_type == 'pay') {
                    this.pay.price_info = Result.result.price_info;
                }
            },
            // 设置选择中的商品的价格、包装费、送的金券
            payItemAttrIdsPrice() {
                if (this.pay.item_attr_ids.length == 0) {
                    this.pay.price_info = this.$nddyny.object.copy(this.pay.price_info_bak);
                    return;
                }
                let item_list = {};
                this.pay.item_attr_ids.forEach(item_attr_id => {
                    let item_attr_info = this.page.item_attr_list[item_attr_id];
                    let seller_user_id = item_attr_info.user_id;
                    let item_id = item_attr_info.item_id;
                    let amount = this.page.cart_list[seller_user_id].items[item_attr_id].amount;
                    if (!item_list[seller_user_id]) {
                        item_list[seller_user_id] = {};
                    }
                    item_list[seller_user_id][item_attr_id] = {
                        item_id,
                        item_attr_id,
                        amount
                    };
                })
                this.$api.post(this, {
                    url: '/seller/ItemCart/priceInfo',
                    data_key: null,
                    data_append: {
                        page_type: this.page_type,
                        seller_type: this.seller_type,
                        buy_mode: this.buy_mode,
                        item_list: JSON.stringify(item_list),
                    },
                    success: (Result, data_key) => {
                        if (this.$api.form.toast(this, Result, data_key)) return;
                        if (Result.result.is_update_cart == '1') {
                            this.command_refresh_dialog.show = true;
                            this.command_refresh_dialog.content = '商品有变';
                            this.command_refresh_dialog.confirm = () => {
                                this.command_refresh_dialog.show = false;
                                this.pageInit();
                            }
                            return;
                        }
                        this.pay.price_info = Result.result.price_info;
                    }
                });
            },
            // 商品详情
            _itemInfoDialogShow(item_info) {
                if (this.page_type == 'item') {
                    this.itemInfoDialogShow(item_info);
                } else if (this.page_type == 'cart' || this.page_type == 'pay') {
                    this.$store.commit('userNavTo', '/seller/item/list?seller_id=' + item_info.seller_user_id +
                        '&buy_mode=' + this.buy_mode +
                        '&item_id=' + item_info.item_id);
                }
            },
            getCartItemAttrList() {
                return this.page.cart_item_attr_list;
            }
        }
    }
</script>
